package y2017.date0929.清理class文件;

import java.io.File;

public class CleanFileUtil {
    public static final int START = 0;
    public static final int CONTAIN = 1;
    public static final int END = 2;

    public void deleteSpecialFile(String dirPath, String speStr) {
        deleteSpecialFile(dirPath, speStr, END);
    }

    /**
     * 删除文件夹下指定后缀名的文件
     *
     * @return boolean
     */
    public void deleteSpecialFile(String dirPath, String speStr, int mode) {

        File dirFile = new File(dirPath);

        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return;
        }

        File[] files = dirFile.listFiles();
        // 遍历删除文件夹下的所有文件(不包括目录)
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (!file.exists()) {
                continue;
            }
            if (file.isFile()) {
                if (!file.getName().endsWith(speStr)) {
                    System.out.println(file.getAbsolutePath() + " is not match to delete.");
                    continue;
                }
                // 删除子文件
                boolean flag = file.delete();
                String flagStr;
                if (flag) {
                    flagStr = " sucess!";
                } else {
                    flagStr = " fail!";
                }
                System.err.println("delete " + file.getAbsolutePath() + flagStr);
            } else if (file.isDirectory()) {
                deleteSpecialFile(file.getAbsolutePath(), speStr, mode);
            } else {
                System.err.println(file.getAbsolutePath() + " is not a file or dir!");
            }
        }
    }

}
